package com.community.backend.controller;

import com.alibaba.fastjson.JSONObject;
import com.alipay.api.request.AlipayTradeRefundRequest;
import com.alipay.api.response.AlipayTradeRefundResponse;
import com.alipay.easysdk.factory.Factory;

import com.community.backend.mapper.FeeMapper;
import com.community.backend.mapper.PropertyFeeMapper;
import com.community.backend.mapper.ShareFeeMapper;
import com.community.backend.pojo.*;


import com.community.backend.properties.AliPayConfig;
import com.community.backend.utils.Result;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.data.relational.core.sql.In;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("alipay")
@Transactional(rollbackFor = Exception.class)
public class AliPayController {

    @Resource
    AliPayConfig aliPayConfig;

//    @Resource
//    private OrderMapper orderMapper;
    @Resource
    private FeeMapper feeMapper;
    @Resource
    private PropertyFeeMapper propertyFeeMapper;
    @Resource
    private ShareFeeMapper shareFeeMapper;
//    private static final String GATEWAY_URL = "https://openapi-sandbox.alipaydev.com/gateway.do";

    private static final String GATEWAY_URL ="https://openapi-sandbox.dl.alipaydev.com/gateway.do";
    private static final String FORMAT ="JSON";
    private static final String CHARSET ="utf-8";
    private static final String SIGN_TYPE ="RSA2";

    @PostMapping("/pay")
    public void pay(@RequestBody AliPay aliPay, HttpServletResponse httpResponse) throws Exception {
        System.out.println("开始执行支付");
        String returnUrl = "http://localhost:5173/#/user/Pay";
        AlipayClient alipayClient = new DefaultAlipayClient(
                GATEWAY_URL,
                aliPayConfig.getAppId(),
                aliPayConfig.getAppPrivateKey(),
                FORMAT,
                CHARSET,
                aliPayConfig.getAlipayPublicKey(),
                SIGN_TYPE
        );

        AlipayTradePagePayRequest request = new AlipayTradePagePayRequest();
        // 1. 设置异步回调地址（不变，用于更新订单状态）
        request.setNotifyUrl(aliPayConfig.getNotifyUrl());
        System.out.println("异步回调地址："+aliPayConfig.getNotifyUrl());
        // 2. 设置同步回调地址
        System.out.println("同步回调地址：fullReturnUrl:"+returnUrl);

        request.setReturnUrl(returnUrl); // 关键：传递参数到前端结果页
        // 3. 组装支付参数（不变）
        request.setBizContent("{\"out_trade_no\":\"" + aliPay.getTraceNo() + "\","
                + "\"total_amount\":\"" + aliPay.getTotalAmount() + "\","
                + "\"subject\":\"" + aliPay.getSubject() + "\","
                + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");

        String form = "";
        try {
            form = alipayClient.pageExecute(request).getBody();
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }

        // 输出表单，跳转支付宝（不变）
        httpResponse.setContentType("text/html;charset=" + CHARSET);
        httpResponse.getWriter().write(form);
        httpResponse.getWriter().flush();
        httpResponse.getWriter().close();
    }
    @PostMapping("/notify")  // 注意这里必须是POST接口
    public String payNotify(HttpServletRequest request) throws Exception {
        if (request.getParameter("trade_status").equals("TRADE_SUCCESS")) {
            System.out.println("=========支付宝异步回调========");

            Map<String, String> params = new HashMap<>();
            Map<String, String[]> requestParams = request.getParameterMap();
            for (String name : requestParams.keySet()) {
                params.put(name, request.getParameter(name));
                // System.out.println(name + " = " + request.getParameter(name));
            }

            String outTradeNo = params.get("out_trade_no");
            System.out.println("outTradeNo"+outTradeNo);
            String gmtPayment = params.get("gmt_payment");
            System.out.println("gmtPayment"+gmtPayment);
            String alipayTradeNo = params.get("trade_no");
            System.out.println("alipayTradeNo"+alipayTradeNo);
            // 支付宝验签
            if (Factory.Payment.Common().verifyNotify(params)) {
                // 验签通过
                System.out.println("交易名称: " + params.get("subject"));
                System.out.println("交易状态: " + params.get("trade_status"));
                System.out.println("支付宝交易凭证号: " + params.get("trade_no"));
                System.out.println("商户订单号: " + params.get("out_trade_no"));
                System.out.println("交易金额: " + params.get("total_amount"));
                System.out.println("买家在支付宝唯一id: " + params.get("buyer_id"));
                System.out.println("买家付款时间: " + params.get("gmt_payment"));
                System.out.println("买家付款金额: " + params.get("buyer_pay_amount"));
                // 更新订单已支付
                String subject = params.get("subject");
                String payment = "支付宝";
                String status = "已缴";
                String tradeNo = params.get("trade_no");
                String buyer_id = params.get("buyer_id");
                String gmt_payment = params.get("gmt_payment");
                if (subject.equals("水费") || subject.equals("电费") || subject.equals("燃气费") || subject.equals("停车费")){
                    feeMapper.updatePayment(outTradeNo,tradeNo,payment,buyer_id,gmt_payment,status);
                }
                if (subject.equals("物业费")){
                    propertyFeeMapper.updatePayment(outTradeNo,tradeNo,payment,buyer_id,gmt_payment,status);
                }
                if (subject.equals("公摊费")){
                    shareFeeMapper.updatePayment(outTradeNo,tradeNo,payment,buyer_id,gmt_payment,status);
                }
            }
        }
        return "success";
    }

    /**
     * 退款
     * @return
     * 问题：我修改数据库状态从已退款到已缴，点击退款，退款成功，但是钱还是只一次
     */
    @PostMapping("/refund")
    public Result refund(@RequestParam String outTradeNo, @RequestParam String project){
        System.out.println("开始执行退款");
        System.out.println("outTradeNo："+outTradeNo);
        if (outTradeNo == null){
            return Result.error("参数错误");
        }
        AlipayClient alipayClient = new DefaultAlipayClient(
                GATEWAY_URL,
                aliPayConfig.getAppId(),
                aliPayConfig.getAppPrivateKey(),
                FORMAT,
                CHARSET,
                aliPayConfig.getAlipayPublicKey(),
                SIGN_TYPE
        );
        AlipayTradeRefundRequest request = new AlipayTradeRefundRequest();
        String tradeNo = "";
        BigDecimal refundAmount = BigDecimal.ZERO;
        String status = "未缴";
        if (project.equals("水费") || project.equals("电费") || project.equals("燃气费") || project.equals("停车费")){
            System.out.println("支付宝退款水电煤气费："+feeMapper.selectById(outTradeNo));
            Fee fee = feeMapper.selectById(outTradeNo);
            tradeNo = fee.getTradeNo();
            refundAmount = fee.getTotalPrice();
            status = fee.getStatus();
        }
        if (project.equals("物业费")){
            PropertyFee propertyFee = propertyFeeMapper.selectById(outTradeNo);
            System.out.println("支付宝退款物业费："+propertyFee);
            tradeNo = propertyFee.getTradeNo();
            refundAmount = propertyFee.getTotalPrice();
            status = propertyFee.getStatus();
        }
        if (project.equals("公摊费")){
            ShareFee shareFee = shareFeeMapper.selectById(outTradeNo);
            System.out.println("支付宝退款公摊费："+shareFee);
            tradeNo = shareFee.getTradeNo();
            refundAmount = shareFee.getTotalPrice();
            status = shareFee.getStatus();
        }
        if (status.equals("未缴")){
            return Result.error("未缴订单不能退款");
        }
// 正确设置退款参数
        JSONObject bizContent = new JSONObject();
        bizContent.put("trade_no", tradeNo);
//        bizContent.put("out_trade_no", outTradeNo);
        bizContent.put("refund_amount", refundAmount);
        bizContent.put("refund_reason", "正常退款");
        request.setBizContent(bizContent.toString());
        System.out.println("退款参数：bizContent："+bizContent);
        try{
            AlipayTradeRefundResponse response = alipayClient.execute(request);
            if(response.isSuccess()){
                System.out.println("退款成功");
                LocalDateTime now = LocalDateTime.now();
                status = "已退款";
                //修改订单状态
                if (project.equals("水费") || project.equals("电费") || project.equals("燃气费") || project.equals("停车费")) {
                    feeMapper.updateStatus(outTradeNo,status,now);
                    System.out.println("支付状态更新成功");
                    return Result.success("退款成功");
                }
                if (project.equals("物业费")) {
                    propertyFeeMapper.updateStatus(outTradeNo,status,now);
                    System.out.println("支付状态更新成功");
                    return Result.success("退款成功");
                }
                if (project.equals("公摊费")){
                    shareFeeMapper.updateStatus(outTradeNo,status,now);
                    System.out.println("支付状态更新成功");
                    return Result.success("退款成功");
                }
                return Result.error("退款成功，但是未找到此订单");
            } else {
                System.out.println("退款失败");
                System.out.println(response.getCode());
                return Result.error(response.getSubMsg());
            }
        }catch (Exception e){
            e.printStackTrace();
            return Result.error("系统异常");
        }
    }

//    @GetMapping("/status")
//    public Result queryOrderStatus(String traceNo) {
//        Orders order = shopOrderMapper.selectById(traceNo);
//        if (order == null) {
//            return Result.error("订单不存在");
//        }
//        return Result.success(order); // 返回订单状态（status字段）
//    }





    @GetMapping("/paya")
    public String pay(String subject, String traceNo, String totalAmount, String returnUrl) throws AlipayApiException {
        // 1. 生成支付宝支付请求
        AlipayClient alipayClient = new DefaultAlipayClient(GATEWAY_URL, aliPayConfig.getAppId(),
                aliPayConfig.getAppPrivateKey(), FORMAT, CHARSET, aliPayConfig.getAlipayPublicKey(), SIGN_TYPE);
        AlipayTradePagePayRequest request = new AlipayTradePagePayRequest();
        System.out.println("88888888888888888888888");
        // 2. 设置同步回调地址（支付完成后跳转回前端结果页）
        request.setReturnUrl(returnUrl); // 关键：使用前端传递的returnUrl

        // 3. 设置异步回调地址（之前的/notify接口，用于更新订单状态）
        request.setNotifyUrl("http://vec968ca.natappfree.cc/alipay/notify");

        // 4. 组装支付参数
        JSONObject bizContent = new JSONObject();
        bizContent.put("out_trade_no", traceNo); // 商户订单号
        bizContent.put("total_amount", totalAmount); // 支付金额
        bizContent.put("subject", subject); // 订单标题
        bizContent.put("product_code", "FAST_INSTANT_TRADE_PAY"); // 固定值
        request.setBizContent(bizContent.toString());

        // 5. 生成支付表单并返回（前端会跳转到支付宝页面）
        return alipayClient.pageExecute(request).getBody();
    }
}